package com.miniapp.aop;

import com.miniapp.annotation.SysLogAnno;
import com.miniapp.entity.MiniLogEntity;

import com.miniapp.entity.MiniUserEntity;
import com.miniapp.service.MiniLogService;
import com.miniapp.utils.BaseUtils;
import com.miniapp.utils.RequestHelper;
import com.miniapp.utils.ShiroUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;


/**
 * 系统日志，切面处理类
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017年3月8日 上午11:07:35
 */
@Aspect
@Component
public class SysLogAspect {

    private static final Logger log = LoggerFactory.getLogger(SysLogAspect.class);

    @Autowired
    private MiniLogService miniLogService;

    private long beginTime =1L;

    @Pointcut("execution(public * com.miniapp.controller..*.*(..)) ")
    //@Pointcut("@annotation(com.miniapp.annotation.SysLogAnno)")
    public void logPointCut() {

    }

    @Before("logPointCut()")
    public void beforeAspect(JoinPoint joinPoint) {

        log.info("*****************系统日志记录*********************");
        beginTime = System.currentTimeMillis();
        HttpServletRequest httpServletRequest = RequestHelper.getCurrentRequest();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        log.info("method:" + method);


        MiniLogEntity miniLog = new MiniLogEntity();
        SysLogAnno sysLogAnno = method.getAnnotation(SysLogAnno.class);
        if (sysLogAnno != null) {
            //注解上的描述
            miniLog.setOperation(sysLogAnno.value());
            log.info("anno:" + sysLogAnno.value());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        miniLog.setMethod(className + "." + methodName + "()");
        log.info("className : " + className);

        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params = null;
        StringBuilder paramSb = new StringBuilder();
        if(args == null && args.length == 0){
            params = null;
        }else{

            for(int i = 0; i < args.length ; i++){
                paramSb.append(args[i].toString());
            }
        }
        miniLog.setParams(paramSb.toString());

        //获取request
        HttpServletRequest request = RequestHelper.getCurrentRequest();
        //设置IP地址
        miniLog.setIp(RequestHelper.getRemoteHost(request));

//        //用户名
        MiniUserEntity sysUser = ShiroUtils.getSysUser();
        String username = "";
        if ("login".equals(methodName)) {
            username = params;
        }
        if (BaseUtils.isNotEmpty(sysUser)) {
            username = sysUser.getUsername();
        }
        miniLog.setUsername(username);

        miniLog.setCreateTime(new Date());

        StringBuilder sb = new StringBuilder();
        sb.append("请求方法【 " + miniLog.getMethod() + " 】 ");
        sb.append("请求参数【 " + miniLog.getParams() + " 】 ");
        sb.append("来源ip【 " + miniLog.getIp() + " 】 ");
        sb.append("用户名【 " + miniLog.getUsername() + " 】 ");
        sb.append("请求时间【 " + miniLog.getCreateTime() + " 】 ");

        if(log.isInfoEnabled()){
            log.info(sb.toString() );
        }

        //保存系统日志
        miniLogService.save(miniLog);
    }

    @After("logPointCut()")
    public void afterAspect(){
        long endtime = System.currentTimeMillis();
        long duration = endtime - beginTime;
        log.info("请求执行时间: " + duration + "毫秒.");
    }

}
